<template>
  <div class="document-container">
    <span class="selection-text">
      {{ selectedFileList.length }} Item Selection
    </span>
    <v-data-table
      v-if="checkedLayout === '2'"
      fixed-header
      v-model="selectedFileList"
      :headers="headers"
      :items="propItems"
      :sort-by.sync="sortByValueSynced"
      :sort-desc.sync="sortDescValueSynced"
      :custom-sort="customSort"
      item-key="id"
      show-select
      class="elevation-0 form-info"
      hide-default-footer
      :items-per-page="-1"
    >
      <template #[`header.data-table-select`]="slotData">
        <div class="d-flex">
          <v-checkbox
            class="mt-0 pt-0 white-check"
            hide-details
            dense
            :indeterminate="slotData.props.indeterminate"
            v-model="slotData.props.value"
            @click="slotData.on.input"
            @change="changAllCheck"
          ></v-checkbox>
        </div>
      </template>
      <template #[`header.name`]>
        <v-icon size="20" color="#fff" class="mr-3"> mdi-folder </v-icon>
        <span> Name </span>
      </template>
      <template #[`header.action`]>
        <div class="d-flex justify-end">
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="pasteData(copiedFiles)"
                v-on="on"
                :disabled="copiedFiles ? false : true"
                size="18"
                color="#fff"
              >
                mdi-clipboard-file
              </v-icon>
            </template>
            Paste File
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="downloadData"
                v-on="on"
                :disabled="selectedFileList.length === 0"
                class="ml-4"
                size="18"
                color="#fff"
              >
                mdi-file-download
              </v-icon>
            </template>
            Download File
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ tooltipOn }">
              <MenuList
                :checked.sync="checkedLayout"
                :items="viewLayoutItems"
                :show-check-icon="true"
              >
                <template #default="{ on }">
                  <v-icon
                    v-on="{ ...tooltipOn, ...on }"
                    class="ml-4"
                    size="18"
                    color="#fff"
                  >
                    mdi-format-list-bulleted
                  </v-icon>
                </template>
              </MenuList>
            </template>
            View Layout
          </v-tooltip>
          <TooltipInfo v-if="propCurrentFolder" title="Detail" width="345">
            <template #default="{ on }">
              <v-icon v-on="on" class="pointer ml-4" color="#fff" size="18">
                mdi-information
              </v-icon>
            </template>
            <template #content>
              <v-spacer class="text-left">
                <v-col class="pa-0 mb-2">
                  <v-row no-gutters>
                    <v-col :cols="5">Type</v-col>
                    <v-col :cols="7">{{ propCurrentFolder.type }}</v-col>
                  </v-row>
                </v-col>
                <v-col class="pa-0 mb-2">
                  <v-row no-gutters>
                    <v-col :cols="5">Size</v-col>
                    <v-col :cols="7">{{ propCurrentFolder.size }}</v-col>
                  </v-row>
                </v-col>
                <v-col class="pa-0 mb-2">
                  <v-row no-gutters>
                    <v-col :cols="5">File Location</v-col>
                    <v-col :cols="7">
                      {{
                        propCurrentFolder.fileLocation
                          ? propCurrentFolder.fileLocation
                          : "-"
                      }}
                    </v-col>
                  </v-row>
                </v-col>
                <v-col class="pa-0 mb-2">
                  <v-row no-gutters>
                    <v-col :cols="5">Modified</v-col>
                    <v-col :cols="7">{{
                      propCurrentFolder.modifiedDate
                    }}</v-col>
                  </v-row>
                </v-col>
              </v-spacer>
            </template>
          </TooltipInfo>
        </div>
      </template>
      <template #[`item.name`]="{ item }">
        <v-icon size="20" color="#79839B" class="mr-3">
          {{ getFileIcon(item.type) }}
        </v-icon>
        {{ item.name }}
      </template>
      <template #[`item.size`]="{ item }">
        <span v-if="item.type !== 'Folder'">
          {{ item.size }}
        </span>
      </template>
      <template #[`item.modifiedDate`]="{ item }">
        <span v-if="item.type !== 'Folder'">
          {{ item.modifiedDate }}
        </span>
      </template>
      <template #[`item.data-table-select`]="slotData">
        <div div class="d-flex">
          <v-checkbox
            @change="slotData.select"
            dense
            hide-details
            class="mt-0 pt-0"
            v-model="slotData.isSelected"
            :class="slotData.isSelected === true ? 'show-icon' : 'action-icon'"
          ></v-checkbox>
        </div>
      </template>
      <template #[`item.action`]="slotData">
        <div class="action-icon d-flex justify-end">
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="copyData([slotData.item])"
                v-on="on"
                size="16"
                class="mr-5"
                color="#79839B"
              >
                mdi-file-multiple
              </v-icon>
            </template>
            Copy File
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="openEditFile(slotData.item)"
                v-on="on"
                size="18"
                class="mr-4 cursor-pointer"
                color="#79839B"
              >
                mdi-square-edit-outline
              </v-icon>
            </template>
            Edit File Name
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="openDeleteFile([slotData.item])"
                v-on="on"
                size="20"
                color="#79839B"
                class="cursor-pointer"
              >
                mdi-delete
              </v-icon>
            </template>
            Delete File
          </v-tooltip>
        </div>
      </template>
    </v-data-table>
    <v-card v-else class="file-container" flat>
      <div class="file-header">
        <div>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="copyData(selectedFileList)"
                v-on="on"
                :disabled="selectedFileList.length === 0"
                size="16"
                class="mr-5"
                color="#fff"
              >
                mdi-file-multiple
              </v-icon>
            </template>
            Copy File
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="openEditFile(selectedFileList[0])"
                v-on="on"
                size="18"
                class="mr-4 cursor-pointer"
                color="#fff"
                :disabled="selectedFileList.length !== 1"
              >
                mdi-square-edit-outline
              </v-icon>
            </template>
            Edit File Name
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="openDeleteFile(selectedFileList)"
                v-on="on"
                :disabled="selectedFileList.length === 0"
                size="20"
                color="#fff"
                class="cursor-pointer mr-4"
              >
                mdi-delete
              </v-icon>
            </template>
            Delete File
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="pasteData(selectedFileList)"
                v-on="on"
                :disabled="copiedFiles ? false : true"
                class="mr-4"
                size="18"
                color="#fff"
              >
                mdi-clipboard-file
              </v-icon>
            </template>
            Paste File
          </v-tooltip>
          <v-tooltip bottom>
            <template v-slot:activator="{ on }">
              <v-icon
                @click="downloadData"
                v-on="on"
                :disabled="selectedFileList.length === 0"
                class="mr-4"
                size="18"
                color="#fff"
              >
                mdi-file-download
              </v-icon>
            </template>
            Download File
          </v-tooltip>
        </div>
        <div class="header-action">
          <v-tooltip bottom>
            <template v-slot:activator="{ tooltipOn }">
              <MenuList
                :checked.sync="checkedLayout"
                :items="viewLayoutItems"
                :show-check-icon="true"
              >
                <template #default="{ on }">
                  <v-icon
                    v-on="{ ...tooltipOn, ...on }"
                    class="ml-4"
                    size="18"
                    color="#fff"
                  >
                    mdi-microsoft
                  </v-icon>
                </template>
              </MenuList>
            </template>
            View Layout
          </v-tooltip>
          <TooltipInfo v-if="propCurrentFolder" title="Detail" width="345">
            <template #default="{ on }">
              <v-icon v-on="on" class="pointer ml-4" color="#fff" size="18">
                mdi-information
              </v-icon>
            </template>
            <template #content>
              <v-spacer class="text-left">
                <v-col class="pa-0 mb-2">
                  <v-row no-gutters>
                    <v-col :cols="5">Type</v-col>
                    <v-col :cols="7">{{ propCurrentFolder.type }}</v-col>
                  </v-row>
                </v-col>
                <v-col class="pa-0 mb-2">
                  <v-row no-gutters>
                    <v-col :cols="5">Size</v-col>
                    <v-col :cols="7">{{ propCurrentFolder.size }}</v-col>
                  </v-row>
                </v-col>
                <v-col class="pa-0 mb-2">
                  <v-row no-gutters>
                    <v-col :cols="5">File Location</v-col>
                    <v-col :cols="7">
                      {{
                        propCurrentFolder.fileLocation
                          ? propCurrentFolder.fileLocation
                          : "-"
                      }}
                    </v-col>
                  </v-row>
                </v-col>
                <v-col class="pa-0 mb-2">
                  <v-row no-gutters>
                    <v-col :cols="5">Modified</v-col>
                    <v-col :cols="7">{{
                      propCurrentFolder.modifiedDate
                    }}</v-col>
                  </v-row>
                </v-col>
              </v-spacer>
            </template>
          </TooltipInfo>
        </div>
      </div>
      <div class="file-content">
        <div v-for="item in propItems" :key="item.id" class="file-box">
          <v-checkbox
            v-model="selectedFileList"
            :value="item"
            class="checkbox"
          ></v-checkbox>
          <div class="file-icon">
            <v-icon
              :class="[item.type === 'Folder' ? 'folder-icon' : 'other-icon']"
            >
              {{ getFileIcon(item.type) }}
            </v-icon>
          </div>
          <div class="file-name">
            {{ item.name }}
          </div>
        </div>
      </div>
    </v-card>
    <Dialog
      @submit="saveFile"
      v-model="showDialog"
      :show-save="step === 1"
      :title="dialogTitle"
      width="480"
    >
      <v-card v-if="step === 1" class="d-flex align-center" flat height="168">
        <v-row no-gutters>
          <v-col cols="3">File Name</v-col>
          <v-col class="text-left" cols="8">
            <v-text-field
              v-model="fileName"
              v-validate="'required'"
              name="File Name"
              class="white-input"
              hide-details
              solo
            ></v-text-field>
            <span class="vee-validate-error">{{
              errors.first("File Name")
            }}</span>
          </v-col>
        </v-row>
      </v-card>
      <Delete
        v-else-if="step === 2"
        @delete="deleteSubmit"
        :title="deleteTitle"
        :subtitle="deleteSubtitle"
      ></Delete>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { Vue, Component, PropSync } from "vue-property-decorator";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import Delete from "@/components/Customer/Dialog/Delete/Delete.vue";
import MenuList from "@/components/Menu/MenuList.vue";
import TooltipInfo from "@/components/TooltipInfo/TooltipInfo.vue";
import { getDate, getTime } from "@/common/constants/Utils";
import { IFile, IFolder } from "@/components/Library/index";
@Component({
  components: {
    Dialog,
    Delete,
    MenuList,
    TooltipInfo,
  },
  props: {
    items: {
      type: Array,
      default: () => [],
    },
    currentFolder: {
      type: Object,
      default: () => ({}),
    },
  },
})
export default class File extends Vue {
  @PropSync("sortByValue", { type: String }) sortByValueSynced!: string;
  @PropSync("sortDescValue", { type: Boolean }) sortDescValueSynced!: boolean;
  checkedLayout = "2";
  viewLayoutItems = [
    {
      id: "1",
      icon: "mdi-microsoft",
      text: "View Larger Icon",
    },
    {
      id: "2",
      icon: "mdi-format-list-bulleted",
      text: "View Details",
    },
  ];
  get propCurrentFolder() {
    return this.$props.currentFolder;
  }
  // table data
  headers = [
    {
      text: "Name",
      value: "name",
    },
    { text: "Modified Date", value: "modifiedDate", sortable: false },
    { text: "Size", value: "size", sortable: false },
    { value: "action", sortable: false },
  ];
  fileLst: Array<IFile> | null = null;
  get propItems(): Array<IFile> {
    this.$set(this, "fileLst", this.$props.items);
    return this.fileLst as Array<IFile>;
  }
  getFileIcon(type: string) {
    switch (type) {
      case "Folder":
        return "mdi-folder";
      case "Pdf":
        return "mdi-file-powerpoint";
      case "Jpg":
        return "mdi-file-image";
      case "Excel":
        return "mdi-file-excel";
      case "Video":
        return "mdi-file-video";
      case "Text":
        return "mdi-file-document";
      default:
        return "mdi-folder";
    }
  }
  // 1.EditFilaName 2.DeleteFile
  step = -1;
  // dialog
  fileName: string | null = null;
  showDialog = false;
  dialogTitle = "";
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }
  // sort
  sortDesc = false;
  sortBy = "size";
  customSort(items: IFile[], [by]: [string], [desc]: [boolean]) {
    // 没排序直接返回
    if (desc === null || desc === undefined) {
      return items;
    }
    return items.sort((item1, item2) => {
      if (by === "modifiedDate") {
        const date1 = new Date(item1.modifiedDate);
        const date2 = new Date(item2.modifiedDate);
        if (desc) {
          return date2 <= date1 ? 1 : -1;
        } else {
          return date1 > date2 ? -1 : 1;
        }
      } else if (by === "size") {
        const size1 = Number(item1.size.split(" KB")[0].split(",").join(""));
        const size2 = Number(item2.size.split(" KB")[0].split(",").join(""));
        console.log(size1, size2);
        if (desc) {
          return size2 <= size1 ? 1 : -1;
        } else {
          return size1 > size2 ? -1 : 1;
        }
      } else if (by === "name") {
        const name1 = item1.name.substring(0, 1);
        const name2 = item2.name.substring(0, 1);
        if (desc) {
          return name2 <= name1 ? 1 : -1;
        } else {
          return name1 > name2 ? -1 : 1;
        }
      }
      return 1;
    });
  }
  // action
  selectedFileList: IFile[] = [];
  copiedFiles: (IFile | IFolder)[] | null = null;
  selectedFile: IFile | null = null;
  changAllCheck(status: boolean) {
    if (status === false) {
      this.selectedFileList = [];
    }
  }
  // delete弹窗的标题
  get deleteTitle() {
    if (this.checkedLayout === "1") {
      this.dialogTitle = "Delete";
      let deleteTitle = "Are you sure to delete this";
      let hasFolder = false;
      let hasFile = false;
      let folderNum = 0;
      let fileNum = 0;
      // 查看文件和文件夹数量是否为复数，且是否有选择文件夹或者文件
      this.selectedFileList.some((file: IFile | IFolder) => {
        if (file.type === "Folder") {
          hasFolder = true;
          folderNum++;
        } else {
          hasFile = true;
          fileNum++;
        }
        // 存在文件夹和文件且数量都为复数则跳出循环
        if (hasFile && hasFolder && folderNum >= 2 && fileNum >= 2) {
          return true;
        }
      });

      if (hasFolder) {
        deleteTitle += " folder";
        this.dialogTitle += " Folder";
        if (folderNum >= 2) {
          deleteTitle += "s";
          deleteTitle = deleteTitle.replace("this", "these");
        }
      }
      if (hasFile) {
        if (hasFolder) {
          deleteTitle += " and";
          this.dialogTitle += " and";
        }
        deleteTitle += " file";
        this.dialogTitle += " File";
        if (fileNum >= 2) {
          deleteTitle += "s";
          deleteTitle = deleteTitle.replace("this", "these");
        }
      }
      return deleteTitle;
    }
    if (this.selectedFile) {
      return `Are you sure to delete this ${
        this.selectedFile.type === "Folder" ? "Folder" : "File"
      }?`;
    } else {
      return "";
    }
  }
  // delete弹窗的副标题
  get deleteSubtitle() {
    if (this.checkedLayout === "1") {
      return this.selectedFileList.map((file) => file.name).join(",");
    } else {
      if (this.selectedFile) {
        return this.selectedFile.name;
      } else {
        return "";
      }
    }
  }
  // 打开删除弹窗
  openDeleteFile(files: (IFile | IFolder)[]) {
    this.step = 2;
    if (this.checkedLayout === "2") {
      this.selectedFile = files[0];
      this.dialogTitle = `Delete ${
        this.selectedFile.type === "Folder" ? "Folder" : "File"
      }`;
    }
    this.openDialog();
  }
  // 删除弹窗中删除按钮绑定的事件
  deleteSubmit() {
    if (this.checkedLayout === "1") {
      this.batchDeleteFile(this.selectedFileList);
    } else {
      this.deleteFile(this.selectedFile);
    }
    this.closeDelete();
  }
  // 批量删除文件和文件夹
  batchDeleteFile(fileList: (IFile | IFolder)[]) {
    fileList.forEach((file) => this.deleteFile(file));
  }
  // 删除文件或者文件夹
  deleteFile(file: IFile | IFolder | null) {
    console.log(file);
    if (file) {
      if (file.type === "Folder") {
        const folderIndex = this.propCurrentFolder.children.findIndex(
          (child: IFolder) => {
            return child.id === file.id;
          }
        );
        this.propCurrentFolder.children.splice(folderIndex, 1);
      } else {
        const fileIndex = this.propCurrentFolder.fileList.findIndex(
          (item: IFile) => {
            return item.id === file.id;
          }
        );
        this.propCurrentFolder.fileList.splice(fileIndex, 1);
      }
    }
  }
  // 关闭删除弹窗
  closeDelete() {
    this.closeDialog();
    this.selectedFile = null;
  }
  // 复制文件或者文件夹
  copyData(files: (IFile | IFolder)[]) {
    this.copiedFiles = files;
  }
  // 粘贴文件或者文件夹
  pasteData(copiedFiles: (IFile | IFolder)[] | null) {
    if (copiedFiles) {
      copiedFiles.forEach((copiedFile) => {
        let num = 0;
        let fileNameAlreadyExists = false;
        // 寻找是否有相同文件名
        for (var i = 0; i < this.propItems.length; i++) {
          const fileName = this.propItems[i].name.replace(/\(\d+\)$/, "");
          if (
            fileName === copiedFile.name ||
            this.propItems[i].name === copiedFile.name
          ) {
            num++;
            fileNameAlreadyExists = true;
          }
        }
        // 如果文件名重复则创建新的文件
        if (fileNameAlreadyExists) {
          copiedFile = Object.assign({}, copiedFile);
          copiedFile.id =
            String(new Date().getTime()) + Math.random() * 1000000000;
          copiedFile.name = `${copiedFile.name}(${num})`;
          copiedFile.modifiedDate = `${getDate("-")} ${getTime(":").substring(
            0,
            5
          )}`;
        }
        // 复制的是文件夹则要在Folder中添加数据
        if (copiedFile.type === "Folder") {
          if (this.propCurrentFolder.children) {
            this.propCurrentFolder.children.push(copiedFile);
          } else {
            this.$set(this.propCurrentFolder, "children", [copiedFile]);
          }
        } else {
          this.propItems.push(copiedFile);
        }
      });
    } else {
      this.SweetAlertService.warning("Please select the file you want to copy");
    }
  }
  // 打开编辑文件名弹窗
  openEditFile(file: IFile) {
    this.step = 1;
    this.openDialog();
    this.dialogTitle = "Edit name";
    this.selectedFile = file;
    this.fileName = file.name;
  }
  // 编辑选中文件的文件名
  editFileName(fileName: string) {
    if (this.selectedFile) {
      this.selectedFile.name = fileName;
    }
  }
  // 下载
  downloadData(files: (IFile | IFolder)[]) {
    if (!files.length) {
      this.SweetAlertService.warning(
        "Please select the file you want to download"
      );
    } else {
      files.forEach((file) => {
        if (file.type === "Folder") {
          const folder = file as IFolder;
          if (folder.fileList) {
            this.downloadData(folder.fileList);
          }
        } else {
          file = file as IFile;
        }
        console.log("download");
      });
    }
  }
  async saveFile() {
    const result = await this.$validator.validate();
    if (result) {
      if (this.step === 1) {
        this.editFileName(this.fileName as string);
      }
      this.closeDialog();
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/components/Library/File/File.scss";
</style>
